package com.zrt.utils.excel;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.zrt.utils.excel.enums.CharsetEnum;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;


/**
 * Csv处理工具类
 *
 * @author 庄锐涛
 * @version 1.0.0
 */
public class CsvUtils extends CsvUtil {

    private static final Logger logger = LoggerFactory.getLogger(CsvUtils.class);

    /**
     * 读取文件的数据并转换为实例对象
     */
    public static <T> List<T> readCsv(MultipartFile file, Class<T> clazz) {
        List<T> dataList = null;
        if (file.equals("") || file.getSize() <= 0) {
            return dataList;
        } else {
            try {
                CsvReader reader = CsvUtil.getReader();
                return reader.read(ResourceUtil.getUtf8Reader(multipartFileToFile(file).getPath()), clazz);
            } catch (Exception ex) {
                logger.error("糟糕啦!出现异常拉,异常信息=", ex);
            } finally {
                return dataList;
            }
        }
    }

    /**
     * CSV文件导出
     */
    public static <T> void writeCsv(List<T> dataList, String fileName, CharsetEnum charsetEnum) {
        if (dataList.isEmpty()) {
            return;
        } else {
            CsvWriter writer = CsvUtil.getWriter(fileName + ".csv", charsetEnum.getCharsetUtil());
            writer.write(dataList);
        }
    }

    /**
     * 将MultipartFile转化为File
     */
    private static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {

        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            logger.error("糟糕啦!出异常拉,异常信息=", e);
        }
    }
}
